<template>
  <div class="messages" ref="msgRef">
    <messageItem
        v-for="message in messages"
        :key="message.id"
        :message="message"
        @picturePreview="handlePreview"
    >
    </messageItem>
    <transition name="fade">
      <picture-preview
          :picture="pic"
          v-model:visible="showPreview"
          v-show="showPreview"
      />
    </transition>
  </div>
</template>

<script>
import {defineComponent, watch, nextTick, ref, reactive, toRefs} from 'vue'
import messageItem from './MessageItem.vue'
import picturePreview from './PicturePreview.vue'
import {isMobile} from "../../utils/helper"

export default defineComponent({
  props: {
    messages: {
      type: Array,
      required: true,
    }
  },
  components: {messageItem, picturePreview},
  setup(props, context) {
    const state = reactive({
      pic: '',
      showPreview: false,
    })

    const msgRef = ref(null)

    const handlePreview = (pic) => {
      console.log("handlePreview", pic)
      state.pic = pic
      state.showPreview = true
    }

    const scrollToBottom = () => {
      setTimeout(() => {
        nextTick(() => {
          msgRef.value.scrollTop = msgRef.value.scrollHeight
        })
      }, 300)
    }

    watch(() => [...props.messages], scrollToBottom)

    const mobile = isMobile()

    return {
      ...toRefs(state),
      msgRef,
      mobile,
      handlePreview
    }
  },
})
</script>

<style>
.messages {
  padding: 0 10px 10px 10px;
  overflow-y: scroll;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  margin: 0;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>
